#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/21 18:35
    Desc  :
--------------------------------------
"""
from bson import json_util
from common.libs.FakerUtils import *
from application import mongo
from servers.servers.VariableServices import get_veriable_by_name


class Headers(mongo.Document):
    """
    请求头
    """

    headersName = mongo.StringField()
    headersValue = mongo.StringField()
    headersDesc = mongo.StringField()
    projectId = mongo.StringField()

    def to_json(self):
        return {
            '_id': eval(json_util.dumps(self.id)),
            'headersName': self.headersName,
            'headersValue': self.headersValue,
            'headersDesc': self.headersDesc,
            'projectId': self.projectId,
        }

    def headerDict(self):
        """
        返回请求头字典
        """
        data = {}
        if isinstance(self.headersValue, str):
            value = self.headersValue
            # index = value.index('$')
            # 1. 判断是否使用变量  2. 判断是否是内置函数
            if '$' in value and 'random' in value:
                index = value.index('$')
                data[self.headersName] = f'{value[:index]}{eval(value[index + 1:])}'
                # 3. 使用自定义变量
            elif '$' in value:
                index = value.index('$')
                nvalue = get_veriable_by_name(variableName = value[index + 1:], projectId = self.projectId)
                data[self.headersName] = f'{value[:index]}{nvalue}'
            else:
                data[self.headersName] = value
        return data